package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.db.UserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@DubboService //加入到dubbo容器
public class UserServiceImpl implements UserService {

    @Autowired //注入dao对象
    private UserMapper userMapper;
    @Override
    public Long save(User user) {

        //加密
        String md5Pwd = SecureUtil.md5(user.getPassword());
        user.setPassword( md5Pwd );
        //user.setCreated(new Date());//用户是不需要输入时间
        //user.setUpdated(new Date());//不需要输入时间

        userMapper.insert(user); //mybatis-plus 保存对象后 会自动的将id返回到实体类
        return user.getId();
    }

    @Override
    public User findByPhone(String phone) {
        QueryWrapper queryWrapper  = new QueryWrapper();
        queryWrapper.eq("mobile" ,phone ) ; //拼接条件
        List<User> list = userMapper.selectList(queryWrapper); //查询数据
        //if(list!=null && list.size()>0){
        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0); //返回第一个
        }
        return null;
    }

    @Override
    public User findById(Long userId) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id",userId);
        User user = userMapper.selectOne(qw);
        return user;
    }

    @Override
    public void update(User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id",user.getId());
        userMapper.update(user,qw);
    }
}
